package br.com.financeiro.filter;

import java.io.IOException;

import javax.servlet.*;

import org.hibernate.SessionFactory;

import br.com.hibernate.util.HibernateUtil;
public class ConexaoHibernateFilter implements Filter{

	private SessionFactory sf;
	
	public void init(FilterConfig  conf) throws ServletException {
		this.sf = HibernateUtil.getGetsessionfactory();
	}

	
	
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		try {
			this.sf.getCurrentSession().beginTransaction();
			chain.doFilter(request, response);
			this.sf.getCurrentSession().getTransaction().commit();
			this.sf.getCurrentSession().close();
			
			
		} catch (Throwable ex) {
			
			try {
				
				if(this.sf.getCurrentSession().getTransaction().isActive()){
					this.sf.getCurrentSession().getTransaction().rollback();
				}
				
			} catch (Throwable e) {
				e.printStackTrace();
				
			}
			
		}
		
		
		
		
	}

	
	
	
	public void destroy() {
		
		
	}



}
